package syllabus.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import syllabus.model.Criteria;
import syllabus.model.PUser;
import syllabus.service.PUserService;

@Controller
public class LoginAct {

	private static final Logger logger = LoggerFactory.getLogger(LoginAct.class);
	
	@Autowired
	private PUserService userService;
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String login(){
		return "/login";
	}
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam String loginName, @RequestParam String password,
			RedirectAttributes redirectAttributes,ModelMap map, HttpServletRequest request){
		
		if(StringUtils.isBlank(loginName)){
			redirectAttributes.addFlashAttribute("error", "用户名不存在");
			return logout();
		}
		if (StringUtils.isBlank(password)) {
			redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
			return logout();
		}
		
		Subject suser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
		token.setRememberMe(true);
		
		String ip = this.getIpAddr(request);
		
		try {
			suser.login(token);
			logger.info(token.getUsername() + " is logined. Ip is {}",ip);
			return "main";
			
		} catch (AuthenticationException e) {
			redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
			e.printStackTrace();
			return logout();
		}
		
/*		Criteria criteria = new Criteria();
		criteria.put("loginName", loginName);
		criteria.put("password", password);
		criteria.put("loginip", this.getIpAddr(request));
		PUser user = this.userService.selectByUser(criteria);
		logger.info("用户{} 登录系统...",loginName);
		if(null != user){
			logger.info("{}登陆成功", user.getLoginName());
			return "main";
		}else{
			return logout();
		}*/
	}
	
	@RequestMapping(value = "/logout")
	public String logout(){
		Subject suser = SecurityUtils.getSubject();
		suser.logout();
		return "redirect:/login";
	}
	
	/**
	 * 取得客户端真实ip
	 * 
	 * @param request
	 * @return 客户端真实ip
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		logger.debug("1- X-Forwarded-For ip={}", ip);
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			logger.debug("2- Proxy-Client-IP ip={}", ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			logger.debug("3- WL-Proxy-Client-IP ip={}", ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			logger.debug("4- HTTP_CLIENT_IP ip={}", ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			logger.debug("5- HTTP_X_FORWARDED_FOR ip={}", ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			logger.debug("6- getRemoteAddr ip={}", ip);
		}
		logger.info("finally ip={}", ip);
		return ip;
	}
}
